﻿
import Request from '../../base/request.js?t=202511041006'
import Storage from '../../base/storage.js?t=202511041006'
import { getBrowserInfo, queryURLParams } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const data = reactive({
        messageTest: "",
        proxy: "",
        loading: true,
        token: "",
        maxCount: 3,
        state: {
            collapsed: false,
            selectedKeys: [''],
            openKeys: [''],
        },
        items: [

        ]
    })
    let params = toRefs(data)


    const methods = {
        tClick: (e) => {
      
            methods.getAllKey(e.path)
            console.log(e,'e')
            if (/\?/.test(e.item.originItemValue.path) == true) {

                if (e.path == '../Home/Portal_2') {

                    getBrowserInfo().catch(err => { console.log(err) }).then(res => {
                        window.open(e.item.originItemValue.path + `&token=${params.token.value}&${e.item.originItemValue.param}`, e.item.originItemValue.target)

                    }).catch(err => {

                        window.open(e.item.originItemValue.path + `&token=${params.token.value}&${e.item.originItemValue.param}`, e.item.originItemValue.target)
                    })
                } else {


                    window.open(e.item.originItemValue.path + `&token=${params.token.value}&${e.item.originItemValue.param}`, e.item.originItemValue.target)
                }

            } else {

                if (e.path == '../Home/Portal_2') {

                    getBrowserInfo().catch(err => { console.log(err) }).then(res => {
                        window.open(e.item.originItemValue.path + `?token=${params.token.value}&${e.item.originItemValue.param}`, e.item.originItemValue.target)

                    }).catch(err => {

                        window.open(e.item.originItemValue.path + `?token=${params.token.value}&${e.item.originItemValue.param}`, e.item.originItemValue.target)
                    })
                } else {

                    window.open(e.item.originItemValue.path + `?token=${params.token.value}&${e.item.originItemValue.param}`, e.item.originItemValue.target)
                }
            }

            Storage.set('menue', e)
        },
        cClick: () => {
            params.state.value.collapsed = !params.state.value.collapsed
            document.getElementById("toggle_sidemenu_l").click();
        },

        getAllKey: (select = '..' + window.location.pathname) => {

            let fselect = ""
            let s = queryURLParams()

            if (s.module) {
                fselect = select + `?module=${s.module}`
            } else {
                fselect = select
            }
            function findNodeWithAncestors(tree, targetKey, keyProp = 'key', pathProp = 'path', childrenProp = 'children') {
                let result = null;


                function search(node, ancestorsKeys, ancestorsIndexes, levelIndex) {
                    // 找到目标节点，返回祖先节点加上自身，并记录索引
                    if (node[pathProp] === targetKey) {
                        return {
                            keys: [...ancestorsKeys, node[keyProp]],
                            indexes: [...ancestorsIndexes, levelIndex]
                        };
                    }

                    if (node[childrenProp] && Array.isArray(node[childrenProp])) {
                        for (let i = 0; i < node[childrenProp].length; i++) {
                            const child = node[childrenProp][i];
                            const found = search(child, [...ancestorsKeys, node[keyProp]], [...ancestorsIndexes, levelIndex], i);
                            if (found) {
                                return found;
                            }
                        }
                    }

                    return null;
                }

                for (let i = 0; i < tree.length; i++) {
                    const root = tree[i];
                    const found = search(root, [], [], i);
                    if (found) {
                        result = found;
                        break;
                    }
                }


                return result ? { keys: result.keys, indexes: result.indexes } : null;
            }
            let res = findNodeWithAncestors(params.items && params.items.value, fselect)

            if (res && res.keys.length > 0) {
                params.state.value.openKeys = res.keys
                params.state.value.selectedKeys = [res.keys[res.keys.length - 1]]
                params.state.value.indexes = res.indexes


                Storage.set('menue', {
                    keyPath: res.keys,
                    key: res.keys[res.keys.length - 1]
                })
            } else {

                let mm = Storage.get('menue') && Storage.get('menue').keyPath || []
                let cc = Storage.get('menue') && Storage.get('menue').key || []
                params.state.value.openKeys = mm
                params.state.value.selectedKeys = [cc]

            }
            setTimeout(() => {

                if (params.state.value.indexes) {
                    let sum = params.state.value.indexes.map(e => e + 1).reduce((pre, cur) => {
                        return pre + cur;
                    }, 0)
                    let s = document.querySelector('.scc')
                    s.scrollTop = (Number(sum) - 1) > 15 ? 100 * (Number(sum) - 1) : 10 * (Number(sum) - 1)

                }

            }, 500)



        },


        init: () => {
            function transformData(data) {
                return data.map(item => {
                    const key = item.NodeId
                    const path = item.Url
                    const label = item.NodeName
                    const icon = item.IconImg ? h('img', { width: '18px', height: '18px', src: item.IconImg }) : null;
                    const target = item.Target
                    const param = item.Param
                    let children = [];
                    if (item.NodeList && item.NodeList.length > 0) {
                        children = transformData(item.NodeList);
                    }

                    return {
                        key,
                        path,
                        label,
                        icon,
                        target,
                        param,
                        ...(children.length > 0 && { children })
                    };
                });
            }
            params.loading.value = true
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

            setTimeout(() => {
                let info = Storage.get('AccountInfo', true)
                Request({
                    url: "/Account/createJwtToken",
                    method: 'post',
                    data: {
                        "userName": info && info.UserNo
                    }
                }).then(res => {



                    Storage.set('token', res.Data,true)
                    params.token.value = res.Data
                    let isMenue = Storage.get('newmenu', true)


                    if (isMenue) {

                        const transformedData = transformData(isMenue);
                        params.items.value = transformedData
                        params.loading.value = false
                        methods.getAllKey()

                    } else {
                        Request({
                            url: "/Account/GetLeftBussinessMenu",
                            method: 'post',
                        }).then(res => {

                            if (res.Code == -100) {
                                setTimeout(() => {
                                    params.maxCount.value--
                                    if (params.maxCount.value == 0) {
                                        return alert('网络繁忙,请刷新后重试')
                                    }
                                    return methods.init()
                                }, 1000)

                            }


                            res.Data = res.Data?.map(e => {
                                return {
                                    ...e,
                                    NodeList: e.NodeList
                                }
                            })
                            Storage.set('newmenu', res.Data, true)

                            const transformedData = transformData(res.Data);


                            params.items.value = transformedData



                            params.loading.value = false
                            methods.getAllKey()


                        })
                    }

                })
            }, 700)

        },

    }

    const template = {
        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end">
                    <a-space>
                        <a-button v-on:click="onBack">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}

export default Composition
